//
//  DYThemeViewController.m
//  BaiSi
//
//  Created by mac on 16/11/7.
//  Copyright © 2016年 DeYi. All rights reserved.
//

#import "DYThemeViewController.h"
#import "DYEssenceCell.h"
#import <AFNetworking.h>
#import "DYThemeItem.h"
#import <MJExtension/MJExtension.h>
#import "DYThemeViewModel.h"
#import <MJRefresh/MJRefresh.h>
#import "DYNewViewController.h"

static NSString * const ID = @"AllCell";

@interface DYThemeViewController ()
@property(nonatomic,strong) NSMutableArray *themeViewModels;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *maxtime;

@end

@implementation DYThemeViewController
#pragma mark - 懒加载
- (AFHTTPSessionManager *)manager {
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (NSMutableArray *)themeViewModels {
    if (_themeViewModels == nil) {
        _themeViewModels = [NSMutableArray array];
    }
    return _themeViewModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册
    [self.tableView registerClass:[DYEssenceCell class] forCellReuseIdentifier:ID];
    
    //内边距
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 35, 0, 49, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    
    //    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = LHColor(215, 215, 215);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //集成上拉,下拉功能
    [self setUpRefreshView];
    
    //加载数据
    [self.tableView.mj_header beginRefreshing];
    
    //监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:DYReloadThemeView object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
  
    
}
#pragma mark - 集成上拉,下拉功能
- (void)setUpRefreshView {
    //下拉刷新
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_header = headerView;
    headerView.automaticallyChangeAlpha = YES;
    
    //上拉加载
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    footer.automaticallyHidden = YES;
    
}

#pragma mark - 刷新当前界面
- (void)reload {
    
    if (self.view.window) {
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - 加载数据
- (void)loadData {
    //取消上拉加载
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSMutableDictionary *paramter = [NSMutableDictionary dictionary];
    NSString *list = @"list";
    if ([self.parentViewController isKindOfClass:[DYNewViewController class]]) {//判断是否属于新帖
        list = @"newlist";
    }
    paramter[@"a"] = list;
    paramter[@"c"] = @"data";
    paramter[@"type"] = @(self.MyThemeType);
    [self.manager GET:DYBaseUrl parameters:paramter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        //记录maxtime
        _maxtime = responseObject[@"info"][@"maxtime"];
        //写入数据到plist
//        [responseObject writeToFile:@"/Users/mac/Desktop/BaiSi/essenceAllCell.plist" atomically:YES];
        //字典数组转模型
        NSMutableArray *tempArray =[DYThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //移除所有数据
        [self.themeViewModels removeAllObjects];
        for (DYThemeItem *item in tempArray) {
            DYThemeViewModel *themeViewModel = [[DYThemeViewModel alloc] init];
            themeViewModel.item = item;
            
            [self.themeViewModels addObject:themeViewModel];
        }
        //刷新表格
        [self.tableView reloadData];
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            //结束刷新
            [self.tableView.mj_header endRefreshing]; 
            LHLog(@"%@",error);
        }
    }];
    
}

#pragma mark - 加载更多数据
- (void)loadMoreData {
    //取消下拉刷新
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSMutableDictionary *paramter = [NSMutableDictionary dictionary];
    NSString *list = @"list";
    if ([self.parentViewController isKindOfClass:[DYNewViewController class]]) {//判断是否属于新帖
        list = @"newlist";
    }
    paramter[@"a"] = list;
    paramter[@"c"] = @"data";
    paramter[@"type"] = @(self.MyThemeType);
    paramter[@"maxtime"] = _maxtime;
    [self.manager GET:DYBaseUrl parameters:paramter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        //结束刷新
        [self.tableView.mj_footer endRefreshing];
        //记录maxtime
        _maxtime = responseObject[@"info"][@"maxtime"];
        //写入数据到plist
//        [responseObject writeToFile:@"/Users/mac/Desktop/BaiSi/essenceMoereDate.plist" atomically:YES];
        //字典数组转模型
        NSMutableArray *tempArray =[DYThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        for (DYThemeItem *item in tempArray) {
            DYThemeViewModel *themeViewModel = [[DYThemeViewModel alloc] init];
            themeViewModel.item = item;
            [self.themeViewModels addObject:themeViewModel];
        }
        //刷新表格
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            //结束刷新
            [self.tableView.mj_footer endRefreshing];
            LHLog(@"%@",error);
        }
    }];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _themeViewModels.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DYEssenceCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.viewModel = _themeViewModels[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DYThemeViewModel *vm = _themeViewModels[indexPath.row];
    return vm.cellHeight + 10;
}

@end
